package com.example.design.b.proxy2.javassist;

import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;

import java.lang.reflect.InvocationTargetException;

/**
 * 代理类构造器
 */
public class ProxyBuilder<T> {

    /**
     * 构建代理对象
     *
     * @param obj 被代理的对象
     *
     * @return 被代理后的对象
     */
    @SuppressWarnings("unchecked")
    public T build(T obj) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        // 代理工厂
        ProxyFactory proxyFactory = new ProxyFactory();
        // 设置需要创建子类的父类
        proxyFactory.setSuperclass(obj.getClass());
        ProxyObject proxyObject = (ProxyObject) proxyFactory.createClass().getDeclaredConstructor().newInstance();
        proxyObject.setHandler(new CommonMethodHandler(obj));
        return (T) proxyObject;
    }
}
